<template>
<view class="container">
    <view class="p-content">
      <view class="item">
          <view class="avatar">
            <view class="head">
              <button open-type="chooseAvatar" @click="onClickAvatar()" @chooseavatar="onChooseAvatar" >
                <image :src="avatarUrl" mode="" />
              </button>
            </view>
            <view class="tips">更换头像</view>
          </view>
      </view>
      <view class="item">
        <view class="label">昵称</view>
        <view class="value un-input">
          <input type="nickname" @blur="blurname" v-model="username" placeholder="请输入昵称"/>
        </view>
      </view>
      <view class="item">
        <view class="label">手机号</view>
        <view class="value un-input">
          <input placeholder="请输入手机号" v-model="mobile" />
        </view>
      </view>
      <view class="item">
        <view class="label">地区</view>
        <view class="value">
          <select-region ref="sRegion"  v-if="((from && from !='')  ||  defaultRegion.length>0)" v-model="region" :column="2" :defaultval="defaultRegion" placeholder="请选择省市"/>
        </view>
      </view>
    </view>
    <view class="btn">
      <button class="button btn-primary" @click="setAvatarName">确定</button>
    </view>
</view>
</template>

<script>
import store from '@/store'
// import SelectRegion from '@/page_work/address/select-region/select-region'
export default {
  // components: {
  //   SelectRegion
  // },
  data() {
    return {
      userId: '',
      avatarUrl: '',
      tempFile: {},
      username: '',
      mobile:'',
      provinceId: '',
      cityId: '',
      region: [],
      defaultRegion: [],
      from:'',
      userInfo:{}
    }
  },
  created() {

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.from = options.from
    console.log(this.from)
    // if(options.from != 'login'){
      this.getUserInfo()
    // }
  },
  methods: {
    getUserInfo(){
      this.$request.get('wx/auth/userInfo').then(res=>{
        const data = res.data;
        this.userId = data.userId;
        this.mobile = data.mobile;
        this.avatarUrl = data.avatarUrl;
        this.username = data.nickName;
        this.defaultRegion = [data.provinceId,data.cityId]
        this.userInfo = data
      })
    },
    onClickAvatar(){
      // #ifdef MP-WEIXIN
      return
      // #endif
      this.chooseImage()
    },
    // 选择头像事件 - 仅限微信小程序
    // #ifdef MP-WEIXIN
    onChooseAvatar({ detail }) {
      const app = this
      // app.avatarUrl = detail.avatarUrl
      app.tempFile = { path: detail.avatarUrl }
      app.uploadFile()
    },
    // #endif

    // 选择图片
    chooseImage() {
      const app = this
      // 选择图片
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success({ tempFiles }) {
          app.tempFile = tempFiles[0]
          app.avatarUrl = app.tempFile.path
        }
      });
    },
    //上传图片
    uploadFile(){
      const app = this;
      this.$request.urlFileUpload('wx/storage/upload',{
        files: [app.tempFile], // 必填 临时文件路径 格式: [{path: "图片地址"}]
        // data:"向服务器传递的参数", //可不填
        // name:"后台接受文件key名称", //默认 file
      }).then(res=>{
        console.log(res)
        this.avatarUrl = res[0].data.url;
      }).catch(err=>{
        this.$toast(err.errmsg)
      })
    },

    setAvatarName(){
      const app = this;
      if(app.avatarUrl == ''){
        app.$toast('请选择头像')
        return;
      }
      if(app.isMobile(app.mobile) == false){
        app.$toast('请输入正确的手机号')
        return;
      }
      if(app.username == ''){
        app.$toast('请输入昵称')
        return;
      }
      if(app.region.length < 2){
        app.$toast('请选择省市')
        return;
      }
      const params = {
        nickName:app.username,
        mobile:app.mobile,
        avatarUrl:app.avatarUrl,
        provinceId:app.region[0].id,
        cityId:app.region[1].id,
      }
      app.$request.post('wx/auth/setNickName',params).then(res=>{
        let o = {
          userName:app.username,
          avatar:app.avatarUrl,
          provinceId:app.region[0].id,
          cityId:app.region[1].id
        }
        store.commit('UPDATE_USER_NAME_AVATAR', o)
        if(app.from == 'login'){
          app.$toast('登录成功')
          // 跳转回原页面
          setTimeout(() => app.onNavigateBack(2), 2000)
        }else if(app.from == 'tips'){
          app.$toast('设置成功')
          // 跳转回原页面
          setTimeout(() => app.onNavigateBack(1), 2000)
        }else{
          app.$toast('设置成功')

        }
      }).catch(err=>{
        app.$toast(err.errmsg)
      })
    },
    onNavigateBack(delta = 1) {
      console.log(delta)
      const pages = getCurrentPages()
      if (pages.length > 1) {
        uni.navigateBack({
          delta: Number(delta || 1)
        })
      } else {
        this.$navTo('pages/index/index')
      }
    },
    isMobile(mobile){
      const reg = /^(1[3456789]\d{9})$/
      return reg.test(mobile)
    },
    blurname(e){
      this.username = e.detail.value
    },
  }
}
</script>

<style scoped lang="scss">
.container{
  position: relative;
  min-height: 100vh;
  padding: 40rpx;
  background: #FFF;
  .p-content{
    //box-sizing: border-box;
    //border-radius: 10rpx;
    background: white;
    padding:40rpx;
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    .item{
      display: flex;
      gap: 20rpx;
      align-items: center;
      border-bottom: 1px solid #F7F7F7;

      &:first-child{
        border-bottom: none;
      }
      .label{
        font-size: 32rpx;
        font-weight: 400;
        color: #242323;
		width: 100rpx;
      }

      .avatar{
        margin: 0 auto;
      }
      .head{
        width: 160rpx;
        height: 160rpx;
        border-radius: 50%;
        overflow: hidden;

        image{
          width: 100%;
          height: 100%;
        }
      }
      .tips{
        text-align: center;
        font-size: 28rpx;
        padding: 20rpx 0 ;
        font-weight: 400;
        color: #FB1F1E;
      }
      .value{
        height: 92rpx;
        overflow: hidden;
        //background: #f1f0f0;
        border-radius: 10rpx;
        box-sizing: border-box;
        flex:1;
        /deep/ .loading{
          height: 92rpx;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        /deep/ .field-value{
          background: #FFF;
        }
      }
      .un-input{
        padding: 26rpx 32rpx;
      }
    }
  }
  button{
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
    background: #f1f0f0;
    &:after{
      display: none;
    }
  }
  .btn{
    position: absolute;
    bottom: 160rpx;
    left: 40rpx;
    right: 40rpx;
    display: flex;
    justify-content: center;
    button{
      width: 100%;
      height: 88rpx;
      background: #1777FF;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 20rpx;
      font-size: 32rpx;
      font-weight: 500;
      color: #FFFFFF;
      &:after{
        display: none;
      }
    }
  }
}
</style>